import axios from 'axios'
import setting from '@/setting'
// 时间戳
// const NewTimeStamp = new Date().getTime()
axios.defaults.timeout = 30000
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
axios.defaults.adapter = function (config) {
  return new Promise((resolve, reject) => {
    wx.showLoading({
      title: '加载中' // 数据请求前loading
    })
    // wx小程序 发起请求相应 log 就可以看到熟悉的返回啦
    var header = {
      'content-type': 'application/json'
    }
    var token = mpvue.getStorageSync('useInfo').token
    if (token) {
      header.token = token
    }
    wx.request({
      url: setting.baseUrl + config.url,
      method: config.method,
      data: config.data,
      header: header,
      success: (res) => {
        if (res.data.errno === 1001) {
          wx.showToast({
            title: 'token失效，请重新登陆',
            icon: 'none',
            duration: 2000
          })
          setTimeout(function () {
            wx.reLaunch({
              url: '/pages/login/main'
            })
            return false
          }, 1000)
        } else {
          wx.hideLoading()
          return resolve(res)
        }
      },
      fail: (err) => {
        wx.hideLoading()
        return reject(err)
      }
    })
  })
}
// axios 拦截器
function Instance () {
  // 请求拦截器
  axios.interceptors.request.use(function (request) {
    return request
  }, function (error) {
    return Promise.reject(error)
  })

  // 添加响应拦截器
  axios.interceptors.response.use(function (res) {
    return res.data
  }, function (error) {
    return Promise.reject(error)
  })
}

Instance()

function getData (data) {
  return axios({
    method: data.method,
    url: data.url,
    data: data.params
  })
}
export default {
  getData
}
